package org.zirco.model.adapters;

import java.util.List;

import org.zirco.utils.ApplicationUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import de.idgard.android.R;
import de.idgard.android.addon.annotation.Intervention;
import de.idgard.android.utils.Base64Encoder;
import de.idgard.webapp.shared.dto.bookmark.BookmarkLinkDto;

@Intervention
public class BookmarkDTOAdapter extends ArrayAdapter<BookmarkLinkDto> {

	Context context;
	int layoutResourceId;
	List<BookmarkLinkDto> data = null;

	public BookmarkDTOAdapter(Context context, int layoutResourceId, List<BookmarkLinkDto> data) {
		super(context, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.data = data;
	}

	public List<BookmarkLinkDto> getData() {
		return data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		BookmarkHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);

			holder = new BookmarkHolder();
			holder.imgIcon = (ImageView) row.findViewById(R.id.BookmarkRow_Thumbnail);
			holder.txtTitle = (TextView) row.findViewById(R.id.BookmarkRow_Title);
			holder.link = (TextView) row.findViewById(R.id.BookmarkRow_Url);

			row.setTag(holder);
		} else {
			holder = (BookmarkHolder) row.getTag();
		}

		BookmarkLinkDto dto = data.get(position);
		holder.txtTitle.setText(dto.getName());

		String iconStr = null;
		if (dto.getIcon() != null && !dto.getIcon().equals("")) {
			String[] splitted = dto.getIcon().split(",");
			iconStr = splitted.length > 1 ? splitted[1] : splitted[0];
		}

		byte[] favicon = dto.getIcon() != null ? (iconStr != null ? Base64Encoder.decode(iconStr) : null) : null;

		BitmapDrawable icon = null;
		if (favicon == null)
			icon = new BitmapDrawable(BitmapFactory.decodeResource(context.getResources(), R.drawable.fav_icn_unknown));
		else
			icon = new BitmapDrawable(BitmapFactory.decodeByteArray(favicon, 0, favicon.length));

		if (icon != null) {
			int mFaviconSize = ApplicationUtils.getFaviconSizeForBookmarks((Activity) context);

			Bitmap bm = Bitmap.createBitmap(mFaviconSize, mFaviconSize, Bitmap.Config.ARGB_4444);
			Canvas canvas = new Canvas(bm);

			icon.setBounds(0, 0, mFaviconSize, mFaviconSize);
			icon.draw(canvas);

			holder.imgIcon.setImageBitmap(bm);
		}

		holder.link.setText(dto.getLink());

		return row;
	}

	public static class BookmarkHolder {
		ImageView imgIcon;
		public TextView txtTitle;
		public TextView link;
	}
}
